﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace FluentlyXml.Core.Deserialization
{
	internal class DeserializationContext : IDeserializationContext
	{
		private readonly FluentDeserializer _deserializer;
		private readonly IDictionary<string, object> _identityMap = new Dictionary<string, object>();

		public DeserializationContext(FluentDeserializer deserializer)
		{
			_deserializer = deserializer;
		}

		private string GetTypeKey(Type type, object key)
		{
			return type.FullName + ":" + key.GetHashCode();
		}

		public void AddObject(object key, ref object obj)
		{
			string typeKey = GetTypeKey(obj.GetType(), key);

			if (_identityMap.ContainsKey(typeKey))
			{
				obj = _identityMap[typeKey];
			}
			else
			{
				_identityMap.Add(typeKey, obj);
			}
		}

		public object FindObject(Type type, object key)
		{
			string typeKey = GetTypeKey(type, key);

			if (_identityMap.ContainsKey(typeKey))
			{
				return _identityMap[typeKey];
			}
			else
			{
				return null;
			}
		}

		public object Deserialize(Type type, XElement xml, IDeserializationContext context)
		{
			return _deserializer.DeserializeInternal(type, xml, context);
		}
	}
}